// src/element/player.ts
export class Player {
  private scalce: number = 10 * 2;
  x: number;
  y: number;
  offsetX: number = 0;
  offsetY: number = 0;
  image: HTMLImageElement;
  startX: number;
  startY: number;
  initX: number;
  initY: number;
  draggable: boolean = true;
  type: number;

  constructor(x: number, y: number, image: HTMLImageElement, type: number) {
    this.x = x;
    this.y = y;
    this.image = image;
    this.startX = x;
    this.startY = y;
    this.initX = x;
    this.initY = y;
    this.type = type;
  }

  setOffset(offsetX: number, offsetY: number) {
    this.offsetX = offsetX;
    this.offsetY = offsetY;
  }

  refreshXY(pos: { x: number; y: number }) {
    if (this.draggable) {
      const newX = pos.x * 2 - this.offsetX;
      const newY = pos.y * 2 - this.offsetY;

      // 限制拖动范围
      const minLeft = 0;
      const maxRight =
        window.innerWidth * 2 -
        this.image.width / this.scalce -
        (this.type == 1 ? 100 : 110) +
        30;
      this.image.width;
      const minTop = 0;
      const maxBottom =
        window.innerHeight * 2 - this.image.height / this.scalce - 300;

      this.x = Math.max(minLeft, Math.min(maxRight, newX));
      this.y = Math.max(minTop, Math.min(maxBottom, newY));
    }
  }

  isInsideImage(pos: { x: number; y: number }) {
    // 将传入的坐标转换为缩放后的坐标
    const scaledPos = {
      x: pos.x * 2,
      y: pos.y * 2,
    };

    return (
      scaledPos.x > this.x &&
      scaledPos.x - 50 < this.x + this.image.width / this.scalce + 20 &&
      scaledPos.y > this.y &&
      scaledPos.y - 70 < this.y + this.image.height / this.scalce + 20
    );
  }

  draw(ctx: CanvasRenderingContext2D) {
    ctx.drawImage(
      this.image,
      this.x,
      this.y,
      this.type == 1 ? 100 : 110,
      this.type == 1 ? 147.5 : 162
    );
  }

  recordStartPosition() {
    this.startX = this.x;
    this.startY = this.y;
  }

  resetPosition() {
    this.x = this.startX;
    this.y = this.startY;
  }
  restInitPosition() {
    this.x = this.initX;
    this.y = this.initY;
  }
  // 新增的 changeImage 方法
  changeImage(newImage: HTMLImageElement) {
    this.image = newImage;
  }
}
